package com.vehiclemanagement.security;

import com.vehiclemanagement.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * JWT身份验证过滤器
 * 拦截请求，验证JWT令牌
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        final String requestTokenHeader = request.getHeader("Authorization");
        
        String username = null;
        String jwtToken = null;

        // 检查是否是模拟令牌（用于开发和测试）
        if (requestTokenHeader != null && requestTokenHeader.equals("Bearer mock-token-for-testing")) {
            log.info("检测到模拟令牌，允许访问");
            
            // 创建一个具有管理员权限的模拟用户
            UserDetails mockUser = new User(
                "admin", 
                "", 
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"))
            );
            
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                mockUser, null, mockUser.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            
            // 在SecurityContext中设置认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            filterChain.doFilter(request, response);
            return;
        }

        // 解析JWT令牌
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtUtil.getUsernameFromToken(jwtToken);
            } catch (ExpiredJwtException e) {
                log.error("JWT令牌已过期: {}", e.getMessage());
            } catch (Exception e) {
                log.error("JWT解析失败: {}", e.getMessage());
            }
        } else {
            log.debug("不包含有效的JWT令牌");
        }

        // 验证令牌
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            // 如果令牌有效，设置认证信息
            if (jwtUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                // 在SecurityContext中设置认证信息
                SecurityContextHolder.getContext().setAuthentication(authentication);
                log.info("已认证用户: {}", username);
            }
        }
        
        filterChain.doFilter(request, response);
    }
} 